package com.example.ch04jdbcuser.provider;

import com.example.ch04jdbcuser.dao.UserInfoDao;
import com.example.ch04jdbcuser.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author:ScorpioWang
 * @date:2021-11-01-08-49
 */
@Component
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserInfoDao dao;
    //创建User对象（框架提供的对象）
    User user=null;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo=null;

        if(s!=null){
            userInfo=dao.findByUserName(s);
            if(userInfo!=null){
                //权限
                List<GrantedAuthority> list=new ArrayList<>();
                //角色必须以"ROLE_"开头
                GrantedAuthority authority=new SimpleGrantedAuthority("ROLE_"+userInfo.getRole());
                list.add(authority);

                //创建User对象（框架提供的对象）
                user=new User(userInfo.getUsername(),userInfo.getPassword(),list);
            }
        }
        return user;
    }
}
